import { tempIndustry } from './tempData'
import { IMap } from '@/utils/map/index'

// @ts-ignore
import parkIconUrl from '@/assets/img/park.png'
// @ts-ignore
import companyIconUrl from '@/assets/img/company.png'

export interface IOpts {
  container: HTMLElement
  instance: any
  accessToken: string
  plugins: string[]
  center: number[]
  zoom: number
  mapPromise: Promise<any>
}

const defaultPlugins = [
  'AMap.Scale',
  'AMap.Autocomplete',
  'AMap.ToolBar',
  'AMap.Geolocation',
  'AMap.Geocoder',
  'AMap.GeoJSON',
]

const randomIndustry = () => {
  const min = 0
  const max = tempIndustry.length
  const index = new Set()
  index.add(Math.floor(Math.random() * (max - min + 1) + min))
  index.add(Math.floor(Math.random() * (max - min + 1) + min))
  index.add(Math.floor(Math.random() * (max - min + 1) + min))
  return [...index].map((d: any) => {
    return tempIndustry[d]?.fullName || ''
  })
}

export default class MyAMap implements IMap {
  private static instance: any
  private accessToken: string
  private plugins: string[]
  private container: HTMLElement
  private center: number[]
  private zoom: number
  private mapPromise: Promise<any>

  constructor(opts: IOpts) {
    const {
      accessToken = 'e545eca006285231e8cc0af65862861e',
      container,
      plugins = [],
      center = [0, 0],
      zoom = 2,
    } = opts
    this.accessToken = accessToken
    this.container = container
    this.plugins = [...defaultPlugins, ...plugins]
    this.center = center
    this.zoom = zoom
    this.mapPromise = this.initMap()
  }

  static getInstance(opts: IOpts) {
    if (!this.instance) {
      this.instance = new MyAMap(opts)
    }
    return this.instance
  }

  private initMap() {
    const { accessToken, container, plugins, center, zoom } = this

    return new Promise((resolve) => {
      // @ts-ignore
      window.AMapLoader.load({
        key: accessToken,
        version: '2.0',
        plugins,

        AMapUI: {
          version: '1.1',
          plugins: ['misc/PoiPicker'],
        },
        Loca: {
          version: '2.0.0', // Loca 版本，缺省 1.3.2
        },
      }).then((AMap: any) => {
        const map = new AMap.Map(container, {
          center,
          zoom,
          mapStyle: 'amap://styles/whitesmoke',
        })
        // @ts-ignore
        window.mapInstance = map
        resolve(map)
      })
    })
  }

  getRelMapPromise() {
    return this.mapPromise
  }

  async renderParkLine(geojson: any) {
    const map = await this.mapPromise
    // @ts-ignore
    const parkGroup = new window.AMap.OverlayGroup()
    // @ts-ignore
    const parkSource = new window.AMap.GeoJSON({
      geoJSON: geojson,
      // @ts-ignore
      getPolyline(feature, lnglats) {
        console.log(
          '%c [ feature ]-112',
          'font-size:13px; background:pink; color:#bf2c9f;',
          feature
        )
        // @ts-ignore
        const polygon = new window.AMap.Polyline({
          path: lnglats,
          strokeColor: '#267bc9',
          borderWeight: 4,
        })

        polygon.setExtData({
          name: feature.properties.name,
        })

        parkGroup.addOverlay(polygon)
      },
    })

    map.add(parkGroup)
    parkGroup.hide()
    return parkGroup
  }

  async renderPolygon(geojson: any, opts: any = {}) {
    const { clickEvent = () => {} } = opts
    // const poligonList = []
    const map = await this.mapPromise
    // @ts-ignore
    const infoWindow = new window.AMap.InfoWindow({ isCustom: true, offset: [0, -10] })
    // @ts-ignore
    const group = new window.AMap.OverlayGroup()
    // @ts-ignore
    const labelsLayer = new window.AMap.LabelsLayer({
      collision: false,
    })

    // @ts-ignore
    const cqSource = new window.AMap.GeoJSON({
      geoJSON: geojson,
      // 还可以自定义getMarker和getPolyline
      // @ts-ignore
      getPolygon(feature, lnglats) {
        // @ts-ignore
        const polygon = new window.AMap.Polygon({
          path: lnglats,
          fillOpacity: 0,
          strokeColor: '#267bc9',
          fillColor: 'red',
          strokeWidth: 1,
        })

        if (feature.properties.name === '渝北区') {
          polygon.setExtData({
            name: feature.properties.name,
            centroid: feature.properties.centroid,
            industry: ['新能源汽车', '旅游服务', '酒店住宿', '大数据', '农业'],
            // zoom,
            // center,
          })
        } else {
          console.log(randomIndustry())

          polygon.setExtData({
            name: feature.properties.name,
            centroid: feature.properties.centroid,
            industry: randomIndustry(),
            // zoom,
            // center,
          })
        }

        polygon.on('mouseover', () => {
          infoWindow.close()
          polygon.setOptions({
            fillOpacity: 0.2,
            fillColor: '#267bc9',
          })
        })

        polygon.on('mouseout', () => {
          polygon.setOptions({
            fillOpacity: 0,
            fillColor: 'red', // '#ccebc5',
          })
        })

        polygon.on('click', () => {
          map.setFitView(polygon)
          map.clearInfoWindow()
          clickEvent({ areaName: feature.properties.name })
        })

        // @ts-ignore
        const labelMarker = new window.AMap.LabelMarker({
          position: feature.properties.centroid,
          opacity: 1,
          zIndex: 2,
          text: {
            content: feature.properties.name,
            direction: 'bottom',
            style: {
              fontSize: 12,
              fillColor: '#fff',
              padding: [3, 10],
              backgroundColor: '#525a7f',
              borderRadius: 20, // 没有生效
              borderColor: '#525a7f',
              borderWidth: 1,
              pointerEvents: 'none',
            },
          },
        })

        labelMarker.on('mouseover', () => {
          infoWindow.close()
          // const { lng, lat } = e.lnglat
          const extData = polygon.getExtData()
          infoWindow.setContent(getInfoContent(extData))
          infoWindow.open(map, extData.centroid)
        })

        labelMarker.on('click', () => {
          map.setFitView(polygon)
          map.clearInfoWindow()
          clickEvent({ areaName: feature.properties.name })
        })

        group.on('mouseout', () => {
          infoWindow.close()
        })

        labelsLayer.add(labelMarker)
        group.addOverlay(polygon)
        // return polygon
      },
    })

    // group.on('click', () => {
    //   clickEvent()
    // })
    console.log(cqSource)

    group.setOptions({
      zooms: [2, 10],
    })

    const getInfoContent = (data: any) => {
      const { industry, name } = data

      let html = ''
      industry.forEach((d: any) => {
        html += `<div class="info-item">${d}</div>`
      })
      return `
        <div class="custom-window-info" style="pointer-events: none;">
        <div class="area-name">${name}</div>
        ${html}
        </div>
      `
    }
    map.add(group)
    map.add(labelsLayer)
    return group
  }

  async fitAreaView(name: string) {
    const map = await this.mapPromise
    const overlays = map.getAllOverlays()
    overlays.forEach((d: any) => {
      const extData = d.getExtData()
      if (extData && extData.name === name) {
        map.setFitView(d)
      }
    })
  }

  async renderParkPoint(geojson: any, opts: any = {}) {
    const { clickEvent = () => {}, iconUrl = parkIconUrl } = opts
    const map = await this.mapPromise
    // @ts-ignore
    const labelsLayer = new window.AMap.LabelsLayer({
      collision: false,
      visible: false,
    })
    // @ts-ignore
    const pointSource = new window.AMap.GeoJSON({
      geoJSON: geojson,
      getMarker(data: any, lnglats: any) {
        const icon = {
          // 图标类型，现阶段只支持 image 类型
          type: 'image',
          // 图片 url
          image: iconUrl,
          // 图片尺寸
          size: [32, 32],
          // 图片相对 position 的锚点，默认为 bottom-center
          anchor: 'center',
        }

        const text = {
          // 要展示的文字内容
          content: data.properties.name,
          // 文字方向，有 icon 时为围绕文字的方向，没有 icon 时，则为相对 position 的位置
          direction: 'bottom',
          // 在 direction 基础上的偏移量
          offset: [0, 0],
          // 文字样式
          style: {
            // 字体大小
            fontSize: 12,
            // 字体颜色
            fillColor: '#22886f',
            // 描边颜色
            strokeColor: '#fff',
            // 描边宽度
            strokeWidth: 2,
          },
        }

        // @ts-ignore
        const labelMarker = new window.AMap.LabelMarker({
          name: '标注2', // 此属性非绘制文字内容，仅最为标识使用
          position: lnglats,
          zIndex: 16,
          // 将第一步创建的 icon 对象传给 icon 属性
          icon,
          // 将第二步创建的 text 对象传给 text 属性
          text,
        })

        labelMarker.on('click', () => {
          clickEvent({ parkName: data.properties.name })
        })

        labelsLayer.add(labelMarker)

        // return labelMarker
      },
    })

    console.log(pointSource)

    map.add(labelsLayer)
    return labelsLayer
  }

  async renderCompanyPoint(geojson: any, opts: any = {}) {
    const { clickEvent = () => {}, iconUrl = companyIconUrl } = opts
    const map = await this.mapPromise
    // @ts-ignore
    const labelsLayer = new window.AMap.LabelsLayer({
      collision: false,
      visible: false,
    })
    // @ts-ignore
    const pointSource = new window.AMap.GeoJSON({
      geoJSON: geojson,
      getMarker(data: any, lnglats: any) {
        const icon = {
          // 图标类型，现阶段只支持 image 类型
          type: 'image',
          // 图片 url
          image: iconUrl,
          // 图片尺寸
          size: [32, 32],
          // 图片相对 position 的锚点，默认为 bottom-center
          anchor: 'center',
        }

        const text = {
          // 要展示的文字内容
          content: data.properties.name,
          // 文字方向，有 icon 时为围绕文字的方向，没有 icon 时，则为相对 position 的位置
          direction: 'right',
          // 在 direction 基础上的偏移量
          offset: [0, 0],
          // 文字样式
          style: {
            fontSize: 12,
            fillColor: '#fff',
            padding: [3, 10],
            backgroundColor: '#1eace6',
            borderRadius: 20, // 没有生效
            borderColor: '#1eace6',
            borderWidth: 1,
            overflow: 'hidden',
            pointerEvents: 'none',
          },
        }

        // @ts-ignore
        const labelMarker = new window.AMap.LabelMarker({
          name: '标注2', // 此属性非绘制文字内容，仅最为标识使用
          position: lnglats,
          zIndex: 16,
          // 将第一步创建的 icon 对象传给 icon 属性
          icon,
          // 将第二步创建的 text 对象传给 text 属性
          text,
        })

        labelMarker.on('click', () => {
          clickEvent({ parkName: data.properties.name })
        })

        labelsLayer.add(labelMarker)

        // return labelMarker
      },
    })

    console.log(pointSource)

    map.add(labelsLayer)
    return labelsLayer
  }

  async clearMap() {
    const map = await this.mapPromise
    map.clearMap()
  }

  async destroy() {
    const map = await this.mapPromise
    map && map.destroy()

    MyAMap.instance = undefined
  }
}
